package com.yunhe.authority.repository.company.dao;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yunhe.authority.domain.company.Employee;
import com.yunhe.authority.repository.company.EmployeeRepository;
import com.yunhe.common.model.PageParam;
import com.yunhe.common.util.StringUtil;
import org.neo4j.ogm.model.Result;
import org.neo4j.ogm.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import com.yunhe.common.util.CollectionUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public class EmployeeDao {

    @Autowired
    private Session session;

    @Autowired
    private EmployeeRepository employeeRepository;

    public Page<Employee> getEmployeeByCondition(Long companyId, String roleType, PageParam pageParam) {
        StringBuffer cql = new StringBuffer();
        //拼接基本语句
        cql.append("match(c:Company)<-[sr:HAS_COMPANY]-(e:Employee)-[:HAS_ROLE]->(r:Role) where 1=1 ");
        cql.append("AND ID(c)=" + companyId);
        //按角色名精确查询
        if (!StringUtil.isEmpty(roleType)) {
            cql.append(" AND (e.name=~'.*" + roleType + ".*' " );
            cql.append(" or e.title=~'.*" + roleType + ".*') ");
        }
        //拼接返回值和Limit部分
        int skip = (pageParam.getPage() - 1) * pageParam.getSize();
        String queryEnd = " RETURN DISTINCT ID(e) as employeeId,e.title as title,e.name as name,e.phone as phone,ID(c) as companyId," +
                "e.createTime as createTime,e.creator as creator,sr.activity as activity" +
                "  order by e.createTime desc SKIP " + skip + " LIMIT " + pageParam.getSize();
        String countEnd = " RETURN count(DISTINCT ID(e))";
        //分页数据查询结果
        Result result = session.query(cql + queryEnd, Maps.newHashMap());
        //查询总数
        Integer total = session.queryForObject(Integer.class,cql + countEnd, Maps.newHashMap());
        //封装为分页类
        List<Employee> employeeList = new ArrayList<>();
        if (result != null) {
            for (Map<String, Object> map : result) {
                employeeList.add(employeeRepository.findById((Long) map.get("employeeId")).orElse(null));
            }
        }

        Page<Employee> page = null;
        if (!CollectionUtil.isEmpty(employeeList)) {
            List<Employee> content = Lists.newArrayList(employeeList);
            Pageable pageable = PageRequest.of(pageParam.getPage() - 1, pageParam.getSize());
            page = new PageImpl<>(content, pageable, total);
        }

        return page;
    }

    /**********************企业*********************/
    /**
     * 根据企业id与角色id查询账号列表 带分页
     * @param companyId 企业id
     * @param roleId    角色id
     * @param keywords  关键词
     * @param pageParam 分页
     * @return Page<Employee>
     */
    public Page<Employee> getEmployeesByCompanyIdAndRoleId(Long companyId, Long roleId, String keywords, PageParam pageParam) {
        StringBuffer cql=new StringBuffer();
        //拼接基本语句
        cql.append("match(c:Company)<-[:HAS_COMPANY]-(e:Employee)-[:HAS_ROLE]->(r:Role) ");
        cql.append(" WHERE ID(c)="+companyId);
        cql.append(" AND ID(r)="+roleId);

        if(!StringUtil.isEmpty(keywords)){
            cql.append(" AND (e.name=~'.*" + keywords + ".*' " );
            cql.append(" or e.title=~'.*" + keywords + ".*') ");
        }

        //拼接返回值和Limit部分
        int skip=(pageParam.getPage()-1)*pageParam.getSize();
        String queryEnd=" RETURN DISTINCT e order by e.createTime desc SKIP "+skip+" LIMIT "+pageParam.getSize();

        String countEnd=" RETURN count(e) ";

        //分页数据查询结果
        Iterable<Employee> employees = session.query(Employee.class,cql.toString()+queryEnd, Maps.newHashMap());
        //查询总数
        Integer total=session.queryForObject(Integer.class,cql.toString()+countEnd, Maps.newHashMap());
        //封装为分页类
        List<Employee> list = Lists.newArrayList(employees);
//        if(result != null){
//            for (Map<String, Object> map : result) {
//                Employee obj = JSONObject.parseObject(JSONObject.toJSONString(map), Employee.class);
//                list.add(obj);
//            }
//        }
        Page<Employee> page = new PageImpl<>(new ArrayList<>());
        if(!CollectionUtil.isEmpty(list)){
            List<Employee> content= Lists.newArrayList(list);
            Pageable pageable= PageRequest.of(pageParam.getPage()-1,pageParam.getSize());
            page=new PageImpl<Employee>(content,pageable,total);
        }
        return page;
    }

    /**
     * 根据企业id与角色id统计账号个数
     * @param companyId 企业id
     * @param roleId 角色id
     * @return Integer
     */
    public Long countEmployeesByCompanyIdAndRoleId(Long companyId, Long roleId) {
        StringBuffer cql=new StringBuffer();
        //拼接基本语句
        cql.append("match(c:Company)<-[:HAS_COMPANY]-(e:Employee)-[:HAS_ROLE]->(r:Role) ");
        cql.append(" where ID(c)="+companyId);
        cql.append(" AND ID(r)="+roleId);

        String countEnd=" RETURN count(e) ";

        //查询总数
        Long total = session.queryForObject(Long.class,cql.toString()+countEnd, Maps.newHashMap());
        return total;
    }
}
